﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace MineGoogleTranslator.Core
{
	public class Translator
	{
		private const string BASE_ADDRESS = "http://translate.google.com/translate_t";
		private const string LANGUAGE = "langpair";
		private const string TEXT = "text";
		private const string REGEX = @"(?<=<div id=result_box dir=""ltr"">[\s\n]*).*(?=[\s\n]*</div></td>)";

		public static String Translate(LanguagePair pair, string text)
		{
			return TranslateText(pair, text);
		}

		private static string TranslateText(LanguagePair pair, string text)
		{
			HttpWebResponse response = CreateTranslatorResponse(pair, text);
			StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF7);
			String html = reader.ReadToEnd();
			response.Close();

			Match match = new Regex(REGEX).Match(html);
			if (match.Success)
				return HttpUtility.UrlDecode(match.Value);
			return "Translation Failed";
		}

		private static HttpWebResponse CreateTranslatorResponse(LanguagePair pair, string text)
		{
			return CreateTranslatorRequest(pair, text).GetResponse() as HttpWebResponse;
		}

		private static HttpWebRequest CreateTranslatorRequest(LanguagePair pair, string text)
		{
			HttpWebRequest request = WebRequest.Create(BASE_ADDRESS + "?" + LANGUAGE + "=" + pair.ToString() + "&" + TEXT + "=" + text) as HttpWebRequest;
			request.ContentType = "text/html;charset=iso-8859-1";
			return request;
		}

		private string UrlEncode(string text)
		{
			return HttpUtility.UrlEncode(text);
		}
	}
}
